package com.jojo.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jojo.store.entity.User;
import com.jojo.store.mapper.UserMapper;
import com.jojo.store.service.IUserService;
import com.jojo.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * 用户业务层实现接口
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user) {
        String regusername = user.getUsername();
//        调用mapper获取对象
        User reguser = userMapper.selectOne(new QueryWrapper<User>().eq("username", regusername));
//首先判断是否有这个用户信息
        if (reguser!=null){
        throw new UsernameDuplicatedException("不好意思，这个用户名已被占用");
        }
//        密码加密处理的实现，MD5算法的形式，：67dasjdjas-dsadsa132-123213weqw-3213-43234
        //（串+password+串） --》md5算法进行加密，连续加载三次
        //盐值+password+盐值-----盐值就是一个随机的字符串
        String oldpassword = user.getPassword();
        //获取盐值（随机生成盐值（串））
        String salt = UUID.randomUUID().toString().toUpperCase();
//        一定要记得把盐值也就是锁的钥匙 存起来，否则无法解码
        user.setSalt(salt);
//        将密码和盐值结合进行加密处理
        String md5Password = getMD5Password(oldpassword,salt);
//        把加密后的密码存进去
        user.setPassword(md5Password);

        //1补全 is_delete设置0等基础设置;
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        int insertrows = userMapper.insert(user);
//        防止错误的发生；
        if (insertrows!=1){
            throw new InsertException("用户再插入过程中出现了未知的异常");
        }

    }

    @Override
    public User login(String username, String password) {
        if (username==null||password==null){
            throw new UnameNotFoundException("请检查输入情况");
        }
        User result = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        //根据用户名称来找用户,如果有则下一步，没有则抛出异常
        if (result==null){
            throw new UnameNotFoundException("用户名不存在");
        }
        //检测用户密码是否匹配
        //1.1首先获取盐值
        String salt = result.getSalt();
        //
        //1,将用户传过来的密码同样用md5进行加密
        String md5Password = getMD5Password(password, salt);
        if (!result.getPassword().equals(md5Password)){
            throw new PwdNotMacthExcpetion("密码不匹配");
        }
        if (result.getIsDelete()==1){
            throw new UnameNotFoundException("用户数据不存在");
        }
//在这重新创建一个新对象专门用来展示此类信息，减少缓存空间、
        //提升系统的性能  数据中转，压缩功能
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());
        return user;
    }

    /**
     * 设置一个MD5加密密码的私有方法
     * @param pass
     * @param salt
     * @return 返回一个加密后的密码
     */
    private String getMD5Password(String pass,String salt){
//        加密三次；
        for (int i = 0; i < 3; i++) {
         pass = DigestUtils.md5DigestAsHex((salt +pass+ salt).getBytes()).toUpperCase();
        }
        return pass;
    }



    @Override
    public void ChangePwd(Integer uid, String username, String oldpassword, String newpassword) {
        if (oldpassword==newpassword||(oldpassword==null||newpassword==null)){

        }

        User result = userMapper.selectOne(new QueryWrapper<User>().eq("uid", uid));
        if (result==null||result.getIsDelete()==1){
            throw new UnameNotFoundException("用户数据不存在");
        }
        if (!result.getPassword().equals(getMD5Password(oldpassword,result.getSalt()))){
            throw new PwdNotMacthExcpetion("密码错误");
        }
        String newMd5Pwd = getMD5Password(newpassword, result.getSalt());
        int flag = userMapper
                .update(null, new UpdateWrapper<User>()
                        .set("password", newMd5Pwd)
                        .eq("uid", uid)
                        .set("modified_user", username)
                        .set("modified_time", new Date()));
        if (flag!=1){
            throw new updateException("更新出现未知异常");
        }
    }

    @Override
    public void changeUserData(Integer uid,String username,User user) {
        User result = userMapper.selectOne(new QueryWrapper<User>().eq("uid", uid));
        if (result==null){
            throw new UnameNotFoundException("用户信息不存在");
        }
        user.setUid(uid);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer integer = userMapper.upUserData(user);
        if (integer!=1){
            throw new updateException("更新出现异常");
        }
    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.selectOne(new QueryWrapper<User>().eq("uid", uid));
        if (result==null){
            throw new UnameNotFoundException("用户信息不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());
        return user;
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
//        先查询当前用户是否存在
        User one = userMapper.selectOne(new QueryWrapper<User>().eq("uid", uid));
        if (one==null||one.getIsDelete()==1){
            throw new UnameNotFoundException("用户数据不存在");
        }
        //没有发生则更新头像
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.set("avatar",avatar).set("modified_user",username).set("modified_time",new Date()).eq("uid",uid);
        int upresult = userMapper.update(null, uw);
        if (upresult!=1){
            throw new updateException("更新时出现未知的异常");
        }
    }


}
